package com.tokenplus.thai.anetwork

import com.tokenplus.thai.data.*
import com.tokenplus.thai.extend.toFullUrlPath
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object ApiToolNetwork {

    private val garlic_loanServiceTool = ApiServiceCreator.create<ApiToolService>()

    suspend fun fetchAppConfig(reqBase: ReqBase) =
        garlic_loanServiceTool.fetchAppConfig(
            ApiUrl.GARLICLOAN_PATH_APP_CONFIG.toFullUrlPath(),
            reqBase
        ).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(
                        RuntimeException("response body is null")
                    )
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}